<template>
	<el-dialog v-model="showModal" :fullscreen="type !== 'image'" :title="title" append-to-body show-close @closed="handleClose" v-bind="$attrs">
		<template v-if="type === 'image'">
			<!-- 图片预览 -->
			<el-image :src="data.downloadUrl" fit="contain" preview-teleported />
		</template>
		<template v-if="type === 'word'">
			<div class="docx-preview" ref="docxPreview" />
		</template>
		<template v-if="type === 'excel'">
			<el-tabs v-model="activeSheet" class="demo-tabs">
				<el-tab-pane v-for="(item, index) in xlsxSheetsNames" :label="item" :name="index" :key="index">
					<div class="xlsx-preview" v-html="xlsxSheetsHtml[item]" />
				</el-tab-pane>
			</el-tabs>
		</template>
		<template v-if="type === 'pdf'">
			<iframe :src="`${data.downloadUrl}${hiddenTool}`" width="100%" height="100%"></iframe>
		</template>
		<template v-if="type === 'video'">
			<video style="width: 100%; height: 100%" ref="audioRef" autoplay controls :src="data.downloadUrl"></video>
		</template>
		<template v-if="type === 'ppt'">
			<div id="MyPpt" style="width: 100%; height: 100%; overflow: auto"></div>
		</template>
		<template v-if="type === 'txt'">
			<my-input v-model="txtData" type="textarea" :rows="30" :readonly="true"></my-input>
		</template>
	</el-dialog>
</template>

<script setup name="MyPreview">
import axios from '@u/axios';
import * as XLSX from 'xlsx';
import { renderAsync } from 'docx-preview';
import { getFileType } from '@u/url';

/**
 * 预览组件
 * @module components/my-preview
 * 使用demo
 * <!-- 文件预览组件 -->
 * <my-preview :data="fileData" @close="fileData = {}" />
 */

const props = defineProps({
	data: {
		type: Object,
		default: () => {}
	}
});

const emits = defineEmits(['close']),
	showModal = computed({
		get: () => {
			return !isEmpty(props.data);
		},
		set: () => {}
	}),
	hiddenTool = '#toolbar=0',
	type = computed(() => getFileType(props.data.downloadUrl)),
	title = computed(() => props.data.fileName + props.data.fileSuffix || '暂无标题'),
	docxPreview = ref(null);

let xlsxSheetsNames = ref([]),
	activeSheet = ref(0),
	xlsxSheetsHtml = ref({}),
	txtData = ref('');

function handleClose() {
	xlsxSheetsNames.value = [];
	xlsxSheetsHtml.value = {};
	activeSheet.value = 0;
	emits('close');
}

async function preView(val) {
	if (type.value == 'ppt') {
		window.$('#MyPpt').pptxToHtml({
			pptxFileUrl: val.downloadUrl, //ppt文件地址
			slidesScale: '100%'
		});
	}

	if (['word', 'excel'].includes(type.value)) {
		const res = await axios({
			method: 'get',
			responseType: 'blob',
			url: val.downloadUrl
		});

		if (!res) return;

		if (['excel'].includes(type.value)) {
			const fileReader = new FileReader();
			fileReader.onload = (e) => {
				if (e.target?.result) {
					let workbook = XLSX.read(new Uint8Array(e.target.result), { type: 'array' }); // 解析数据
					activeSheet.value = 0;
					xlsxSheetsNames.value = workbook.SheetNames;
					// 该文件每个工作表名字
					// workbook.Sheets;  该文件每个工作表下的内容
					// XLSX.utils.sheet_to_html 转为html
					// console.log(workbook);
					for (const key in workbook.Sheets) {
						if (Object.hasOwnProperty.call(workbook.Sheets, key)) {
							if (workbook.Sheets[key]['!ref']) {
								//sheet页不为空模板时
								xlsxSheetsHtml.value[key] = XLSX.utils.sheet_to_html(workbook.Sheets[key]);
							}
						}
					}
				}
			};
			fileReader.readAsArrayBuffer(res?.data || res);
			return;
		}
		if (['word'].includes(type.value)) {
			const fileReader = new FileReader();
			fileReader.onload = (e) => {
				if (e.target?.result) {
					renderAsync(e.target?.result, docxPreview.value, null, {
						options: {
							className: type.value, // 默认和文档样式类的类名/前缀
							inWrapper: TextTrackCueList, // 启用围绕文档内容渲染包装器
							ignoreWidth: false, // 禁止页面渲染宽度
							ignoreHeight: false, // 禁止页面渲染高度
							ignoreFonts: false, // 禁止字体渲染
							breakPages: true, // 在分页符上启用分页
							ignoreLastRenderedPageBreak: true, //禁用lastRenderedPageBreak元素的分页
							experimental: false, //启用实验性功能（制表符停止计算）
							trimXmlDeclaration: true, //如果为真，xml声明将在解析之前从xml文档中删除
							debug: false // 启用额外的日志记录
						}
					});
				}
			};
			fileReader.readAsArrayBuffer(res?.data || res);
			return;
		}
		if (type.value === 'txt') {
			const fileReader = new FileReader();
			fileReader.onload = (e) => {
				if (e.target?.result) {
					txtData.value = e.target.result;
				}
			};
			fileReader.readAsText(res?.data || res);
		}
	}
}

onMounted(() => {
	preView(props.data);
});
onUpdated(() => {
	preView(props.data);
});
</script>

<style lang="scss">
.el-dialog.is-fullscreen {
	display: flex;
	flex-direction: column;

	.el-dialog__body {
		flex: 1;
		height: 0;
		overflow: auto;

		.slides-loadnig-msg {
			display: none !important;
		}
	}
}

.xlsx-preview {
	:deep(tr:nth-child(1)) {
		background: gainsboro;
	}

	:deep(table) {
		width: 100%;
		border-right: 1px solid black;
		border-bottom: 1px solid black;
	}

	:deep(td) {
		border-top: 1px solid black;
		border-left: 1px solid black;
	}
}
</style>
